#include <iostream>
#include <string>
#include <sstream>
#include <jsoncpp/json/json.h>

// json实现序列化
std::string serialize() 
{
    // 1.创建一个json::value对象用来存储数据
    Json::Value root;
    // 2.给该value对象中插入数据
    root["name"] = "张三";
    root["sex"] = "男";
    root["age"] = 18;
    root["hobby"].append("swim");
    root["hobby"].append("run");
    root["hobby"].append("sleep");
    // 3.实例化一个工厂
    Json::StreamWriterBuilder builder;
    // 4.由工厂生产一个streamwriter对象
    Json::StreamWriter *writer = builder.newStreamWriter();
    // 5.使用该writer对象进行序列化
    std::stringstream ss;
    writer->write(root, &ss);
    std::cout << ss.str() << std::endl;
    delete writer;
    return ss.str();
}

// json 实现反序列化
void deserialize(std::string str)
{
    // 1.创建Json::value对象
    Json::Value root;
    // 2.实例化CharReaderBuilder工厂类
    Json::CharReaderBuilder builder;
    // 3.用该工厂生产一个CharReader对象
    Json::CharReader *reader = builder.newCharReader();
    // 4.使用该对象对json串进行反序列化，将数据写入到Json::Value中
    std::string err;
    bool ret = reader->parse(str.c_str(), str.c_str() + str.size(), &root, &err);
    if(!ret) {
        std::cout << "deserialize error->" << err << std::endl;
        return;
    }
    std::cout << "name-> " << root["name"].asString() << std::endl;
    std::cout << "age-> " << root["age"].asInt() << std::endl;
    std::cout << "sex-> " << root["sex"].asString() << std::endl;
    int sz = root["hobby"].size();
    std::cout << "hobby-> ";
    for(int i=0; i<sz; i++) {
        std::cout << root["hobby"][i].asString() << " ";
    }
    std::cout << std::endl;
    delete reader;
}

int main()
{
    std::string str = serialize();
    deserialize(str);

    return 0;
}